package com.zhicheng.interceptors;

import com.zhicheng.constant.JwtClaimsConstant;
import com.zhicheng.utils.JwtUtil;
import com.zhicheng.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从请求头中获取令牌
        String token = request.getHeader("Authorization");
        //2、校验令牌
        try {
            // 从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if (redisToken == null){
                // token已失效
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            ThreadLocalUtil.setCurrentId(userId);
            //3、通过，放行
            return true;
        } catch (Exception e) {
            //不通过，http响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
